#!/usr/bin/python
# -*- coding: utf-8 -*-
import operator
from functools import reduce
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect,StreamingHttpResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.views.decorators import csrf
from django.contrib.auth.decorators import login_required
from django import forms
from assets import models
from django.db.models import Q
from IPy import IP
from django.contrib import messages
from django.core import serializers

# Create your views here.

@login_required(login_url='/login/')
def getdata(request):
    datacenter = get_object_or_404(models.DataCenter,name=request.GET['datacenter'])
    machineroom = models.MachineRoom.objects.filter(datacenter=datacenter)
    data = serializers.serialize('json', machineroom)
    return HttpResponse(data, content_type='application/json')

@login_required(login_url='/login/')
def getdatacenter(request):
    datacenter = models.DataCenter.objects.all()
    data = serializers.serialize('json', datacenter)
    return HttpResponse(data, content_type='application/json')

@login_required(login_url='/login/')
def index(request):
    assets = models.Asset.objects.all()
    return render(request, 'assets/server.html', { 'assets':assets })

@login_required(login_url='/login/')
def ajax_bar(request):
    if request.session["bar"] == 0:
        request.session["bar"] = 1
    else:
        request.session["bar"] = 0
    return HttpResponse("success")

@login_required(login_url='/login/')
def dashboard(request):
    total = models.Asset.objects.count()
    upline = models.Asset.objects.filter(status=0).count()
    offline = models.Asset.objects.filter(status=1).count()
    unknown = models.Asset.objects.filter(status=2).count()
    breakdown = models.Asset.objects.filter(status=3).count()
    backup = models.Asset.objects.filter(status=4).count()
    up_rate = round(upline/total*100) if total !=0 else 0
    o_rate = round(offline/total*100) if total !=0 else 0
    un_rate = round(unknown/total*100) if total !=0 else 0
    bd_rate = round(breakdown/total*100) if total !=0 else 0
    bu_rate = round(backup/total*100) if total !=0 else 0
    server_number = models.Asset.objects.filter(asset_type='server').count()
    networkdevice_number = models.Asset.objects.filter(asset_type='networkdevice').count()
    datacenter_number = models.DataCenter.objects.count()
    cabinet_number = models.Cabinet.objects.count()
    cabinet_self_number = models.Cabinet.objects.filter(user=0).count()
    cabinet_other_number = models.Cabinet.objects.filter(user=1).count()
    datacenter = models.DataCenter.objects.all()
    server_in_datacenter={}
    networkdevice_in_datacenter={}
    cabinet_in_datacenter={}
    cabinet_self_in_datacenter={}
    cabinet_other_in_datacenter={}
    for item in datacenter:
        value_server = models.Asset.objects.filter(asset_type='server',idc=item).count()
        value_networkdevice = models.Asset.objects.filter(asset_type='networkdevice',idc=item).count()
        value_cabinet = models.Cabinet.objects.filter(datacenter=item).count()
        value_cabinet_self = models.Cabinet.objects.filter(datacenter=item,user=0).count()
        value_cabinet_other = models.Cabinet.objects.filter(datacenter=item,user=1).count()
        key_server = models.DataCenter.objects.get(name=item)
        server_in_datacenter[key_server.name]=value_server
        networkdevice_in_datacenter[key_server.name]=value_networkdevice
        cabinet_in_datacenter[key_server.name]=value_cabinet
        cabinet_self_in_datacenter[key_server.name]=value_cabinet_self
        cabinet_other_in_datacenter[key_server.name]=value_cabinet_other
    return render(request, 'assets/dashboard.html', locals())

@login_required(login_url='/login/')
def server(request):
    if request.GET:
       name=request.GET['name']
       name_split = name.split()
       name_qlist = []
       for key in name_split:
           name_qlist.append(Q(name__icontains=key))
       if name_qlist:
          name_assets = models.Asset.objects.filter(reduce(operator.or_, name_qlist))
       else:
          name_assets = models.Asset.objects.all()
       sn=request.GET['sn']
       sn_split = sn.split()
       sn_qlist = []
       for key in sn_split:
           sn_qlist.append(Q(sn__icontains=key))
       if sn_qlist:
          sn_assets = models.Asset.objects.filter(reduce(operator.or_,sn_qlist))
       else:
          sn_assets = models.Asset.objects.all()
       idc=request.GET['idc']
       business_unit = request.GET['business_unit']
       cabinet = request.GET['cabinet']
       modelnumber = request.GET['modelnumber']
       manufacturer = request.GET['manufacturer']
       status = request.GET['status']
       manage_ip = request.GET['manage_ip']
       application = request.GET['application']
       operation =request.GET['operation']
       qlist=[Q(business_unit__icontains=business_unit),Q(status__icontains=status),Q(application__icontains=application),Q(asset_type='server')]
       if operation:
          qlist.append(Q(operation__username__icontains=operation))
       else:
          qlist.append(Q(operation__username__icontains=operation) | Q(operation__username__isnull=True))
       if cabinet:
          qlist.append(Q(cabinet__name__icontains=cabinet))
       else:
          qlist.append(Q(cabinet__name__icontains=cabinet) | Q(cabinet__name__isnull=True))
       if modelnumber:
          qlist.append(Q(modelnumber__name__icontains=modelnumber))
       else:
          qlist.append(Q(modelnumber__name__icontains=modelnumber) | Q(modelnumber__name__isnull=True))
       if manage_ip:
          qlist.append(Q(manage_ip__icontains=manage_ip))
       else:
          qlist.append(Q(manage_ip__icontains=manage_ip) | Q(manage_ip__isnull=True))
       if idc:
          qlist.append(Q(idc__name__icontains=idc))
       else:
          qlist.append(Q(idc__name__icontains=idc) | Q(idc__name__isnull=True))
       if manufacturer:
          qlist.append(Q(manufacturer__name__icontains=manufacturer))
       else:
          qlist.append(Q(manufacturer__name__icontains=manufacturer) | Q(manufacturer__name__isnull=True))
       other_assets = models.Asset.objects.filter(reduce(operator.and_, qlist))
       assets = other_assets & name_assets & sn_assets
       return render(request, 'assets/server.html',{'assets':assets} )
    else:
       return render(request, 'assets/server.html')

@login_required(login_url='/login/')
def datacenter(request):
    if request.GET:
       name=request.GET['name']
       shortname=request.GET['shortname']
       admin=request.GET['admin']
       contactnumber = request.GET['contactnumber']
       address = request.GET['address']
       datacenter = models.DataCenter.objects.filter(name__icontains=name,shortname__icontains=shortname,admin__username__icontains=admin,contactnumber__icontains=contactnumber,address__icontains=address)
       return render(request, 'assets/datacenter.html',{'datacenter':datacenter} )
    else:
       return render(request, 'assets/datacenter.html')

@login_required(login_url='/login/')
def cabinet(request):
    if request.GET:
       name=request.GET['name']
       name_split = name.split()
       name_qlist = []
       for key in name_split:
           name_qlist.append(Q(name__icontains=key))
       if name_qlist:
          name_cabinet = models.Cabinet.objects.filter(reduce(operator.or_, name_qlist))
       else:
          name_cabinet = models.Cabinet.objects.all()
       datacenter=request.GET['datacenter']
       machineroom=request.GET['machineroom']
       slotcount = request.GET['slotcount']
       user = request.GET['user']
       status = request.GET['status']
       power = request.GET['power']
       memo = request.GET['memo']
       other_cabinet = models.Cabinet.objects.filter(machineroom__datacenter__name__icontains=datacenter,machineroom__name__icontains=machineroom,slotcount__icontains=slotcount,user__icontains=user,status__icontains=status,power__icontains=power,memo__icontains=memo)
       cabinet = other_cabinet & name_cabinet
       return render(request, 'assets/cabinet.html',{'cabinet':cabinet} )
    else:
       return render(request, 'assets/cabinet.html')

@login_required(login_url='/login/')
def ipnet(request):
    if request.GET:
        name = request.GET['name']
        name_split = name.split()
        name_qlist = []
        for key in name_split:
            name_qlist.append(Q(name__icontains=key))
        if name_qlist:
           name_ipnet = models.IpNet.objects.filter(reduce(operator.or_, name_qlist))
        else:
           name_ipnet = models.IpNet.objects.all()
        gw_ip = request.GET['gw_ip']
        isp = request.GET['isp']
        ipnet_status = request.GET['ipnet_status']
        ipnet_type = request.GET['ipnet_type']
        vlan = request.GET['vlan']
        ipnet_customer = request.GET['ipnet_customer']
        business_type = request.GET['business_type']
        split_status = request.GET['split_status']   
        qlist=[Q(isp__icontains=isp),Q(ipnet_status__icontains=ipnet_status),Q(ipnet_type__icontains=ipnet_type),Q(ipnet_customer__icontains=ipnet_customer),Q(split_status__icontains=split_status),Q(business_type__icontains=business_type)]
        if gw_ip:
          qlist.append(Q(gw_ip__icontains=gw_ip))
        else:
          qlist.append(Q(gw_ip__icontains=gw_ip) | Q(gw_ip__isnull=True))
        if vlan:
           qlist.append(Q(vlan__icontains=vlan))
        else:
           qlist.append(Q(vlan__icontains=vlan) | Q(vlan__isnull=True))
        other_ipnet = models.IpNet.objects.filter(reduce(operator.and_, qlist))
        ipnet = other_ipnet & name_ipnet
        return render(request, 'assets/ipnet.html',{'ipnet':ipnet} )     
    elif request.POST:
         if request.POST.get('submit') == 'addgw':
            name = request.POST['name']
            gw_ip = request.POST['gw_ip']
            reason = request.POST['reason']
            if gw_ip in IP(name):
               try:
                  models.IpNet.objects.filter(name=name).update(gw_ip=gw_ip)
               except:
                  messages.error(request,"网段不存在")
                  return HttpResponseRedirect('/ipnet')
               else:
                  ipnet = models.IpNet.objects.get(name=name)
                  detail = '网段添加网关%s' %gw_ip
                  ipeventlog = models.IpEventLog(ipnet=ipnet,event_type=1,reason=reason,detail=detail,user=request.user)
                  ipeventlog.save()
                  messages.success(request,"网关添加成功")
                  return HttpResponseRedirect('/ipnet')
            else:
               messages.error(request,"网关不在网段内")
               return HttpResponseRedirect('/ipnet')
         elif request.POST.get('submit') == 'ipnet_split':
            name = request.POST['name']
            ipnet = get_object_or_404(models.IpNet,name=name)
            ips = IP(name)
            try:
               for key in ips:
                 ipaddress = models.IpAddress()
                 ip = str(key)
                 try:
                    temp_ip = get_object_or_404(models.IpAddress,name=ip)
                 except:
                    ipaddress.name = ip
                    ipaddress.netmask = IP(name).strNetmask()
                    ipaddress.ipnet = ipnet
                    ipaddress.ipaddress_status = 1
                    ipaddress.save()  
                    detail = '网段裂解'
                    ipeventlog = models.IpEventLog(ipaddress=ipaddress,event_type=0,detail=detail,user=request.user)
                    ipeventlog.save()
                 else:
                    messages.error(request,"IP %s已经存在" %key)
                    return HttpResponseRedirect('/ipnet')
            except:
               messages.error(request,"裂解失败")
               return HttpResponseRedirect('/ipnet')
            else:
               models.IpNet.objects.filter(name=name).update(split_status=0)
               ipnet = models.IpNet.objects.get(name=name)
               detail = '网段裂解'
               reason = request.POST['reason']
               ipeventlog = models.IpEventLog(ipnet=ipnet,event_type=1,reason=reason,detail=detail,user=request.user)
               ipeventlog.save()
               messages.success(request,"裂解成功")
               return HttpResponseRedirect('/ipnet')
         elif request.POST.get('submit') == 'ipnet_del':
            name = request.POST['name']
            ipaddress = models.IpAddress.objects.filter(ipnet__name=name)
            for ip in ipaddress:
                if ip.asset:
                   messages.error(request,"删除失败，IP%s存在分配关系" %ip)
                   return HttpResponseRedirect('/ipnet')
            ipnet = get_object_or_404(models.IpNet,name=name)
            models.IpNet.objects.filter(name=name).delete()
            return HttpResponseRedirect('/ipnet')
    else:
        return render(request, 'assets/ipnet.html')

@login_required(login_url='/login/')
def ipnetdetail(request,ipnet_id):
    if request.POST:
       if request.POST.get('submit') == 'addgw':
          ipnet = get_object_or_404(models.IpNet,id=ipnet_id)
          gw_ip = request.POST['gw_ip']
          reason = request.POST['reason']
          if gw_ip in IP(ipnet.name):
             models.IpNet.objects.filter(id=ipnet_id).update(gw_ip=gw_ip)
             ipnet = models.IpNet.objects.get(id=ipnet_id)
             detail = '网段添加网关%s' %gw_ip
             ipeventlog = models.IpEventLog(ipnet=ipnet,event_type=1,reason=reason,detail=detail,user=request.user)
             ipeventlog.save()
             messages.success(request,"网关添加成功")
             return HttpResponseRedirect('/ipnetdetail/%s' %ipnet_id)
          else:
             messages.error(request,"网关不在网段内")
             return HttpResponseRedirect('/ipnetdetail/%s' %ipnet_id)
       elif request.POST.get('submit') == 'ipnet_edit':
          ipnet = models.IpNet.objects.get(id=ipnet_id)
          oldipnet = models.IpNet.objects.get(id=ipnet_id)
          gw_ip = request.POST['gw_ip']
          ipnet.vlan = request.POST['vlan'] if request.POST['vlan'] else None
          ipnet.isp=request.POST['isp']
          ipnet.ipnet_status=request.POST['ipnet_status']
          ipnet.ipnet_type=request.POST['ipnet_type']
          ipnet.business_type=request.POST['business_type']
          ipnet.ipnet_customer=request.POST['ipnet_customer']
          ipnet.memo=request.POST['memo']
          if gw_ip:
             if gw_ip in IP(ipnet.name):
                gw_ip = gw_ip
             else:
                messages.error(request,"网关输入错误")
                return HttpResponseRedirect('/ipnetdetail/%s' %ipnet_id)
          else:
             gw_ip = None 
          try:
             ipnet.save()
          except:
             messages.error(request,"修改失败")
             return HttpResponseRedirect('/ipnetdetail/%s' %ipnet_id)
          else:
             ipnet_new = models.IpNet.objects.get(id=ipnet_id)
             detaillist=[]
             if oldipnet.gw_ip != ipnet_new.gw_ip:
                change = '网关由“%s”修改为“%s”' %(oldipnet.gw_ip,ipnet_new.gw_ip)
                detaillist.append(change)
             if oldipnet.ipnet_status != ipnet_new.ipnet_status:
                change = '状态由“%s”修改为“%s”' %(oldipnet.get_ipnet_status_display(),ipnet_new.get_ipnet_status_display())
                detaillist.append(change)
             if oldipnet.ipnet_type != ipnet_new.ipnet_type:
                change = '类型由“%s”修改为“%s”' %(oldipnet.get_ipnet_type_display(),ipnet_new.get_ipnet_type_display())
                detaillist.append(change) 
             if oldipnet.ipnet_customer != ipnet_new.ipnet_customer:
                change = '客户由“%s”修改为“%s”' %(oldipnet.ipnet_customer,ipnet_new.ipnet_customer)
                detaillist.append(change)
             if oldipnet.vlan != ipnet_new.vlan:
                change = '网关由“%s”修改为“%s”' %(oldipnet.vlan,ipnet_new.vlan)
                detaillist.append(change)
             if oldipnet.business_type != ipnet_new.business_type:
                change = '业务由“%s”修改为“%s”' %(oldipnet.get_business_type_display(),ipnet_new.get_business_type_display())
                detaillist.append(change)
             if oldipnet.memo != ipnet_new.memo:
                change = '备注由“%s”修改为“%s”' %(oldipnet.memo,ipnet_new.memo)
                detaillist.append(change)
             detail = '; '.join(detaillist)
             if detail:
                ipeventlog = models.IpEventLog(ipnet=ipnet,event_type=1,reason=request.POST['reason'],detail=detail,user=request.user)
                ipeventlog.save()
                return HttpResponseRedirect('/ipnetdetail/%s' %ipnet_id)
             else:
                messages.error(request,"数据无变化")
                return HttpResponseRedirect('/ipnetdetail/%s' %ipnet_id)
    else:
      ipnet = get_object_or_404(models.IpNet,id=ipnet_id)
      ipaddress = models.IpAddress.objects.filter(ipnet_id=ipnet_id)
      ipeventlog = models.IpEventLog.objects.filter(ipnet_id=ipnet_id)
      return render(request, 'assets/ipnetdetail.html',{'ipnet':ipnet,'ipaddress':ipaddress,'ipeventlog':ipeventlog})


@login_required(login_url='/login/')
def ipaddress(request):
    if request.GET:
        name = request.GET['name']
        name_split = name.split()
        name_qlist = []
        for key in name_split:
            name_qlist.append(Q(name__icontains=key))
        if name_qlist:
            name_ipaddress = models.IpAddress.objects.filter(reduce(operator.or_, name_qlist))
        else:
            name_ipaddress = models.IpAddress.objects.all()
        isp = request.GET['isp']
        ipaddress_status = request.GET['ipaddress_status']
        vlan = request.GET['vlan']
        ipaddress_customer = request.GET['ipaddress_customer']
        ipnet = request.GET['ipnet']
        qlist=[Q(ipnet__isp__icontains=isp),Q(ipaddress_status__icontains=ipaddress_status),Q(ipaddress_customer__icontains=ipaddress_customer),Q(ipnet__name__icontains=ipnet)]
        if vlan:
           qlist.append(Q(vlan__icontains=vlan))
        else:
           qlist.append(Q(vlan__icontains=vlan) | Q(vlan__isnull=True))
        #other_ipaddress = models.IpAddress.objects.filter(ipnet__isp__icontains=isp,ipaddress_status__icontains=ipaddress_status,ipnet__vlan__icontains=vlan,ipaddress_customer__icontains=ipaddress_customer,ipnet__name__icontains=ipnet)
        other_ipaddress = models.IpAddress.objects.filter(reduce(operator.and_, qlist))
        ipaddress = other_ipaddress & name_ipaddress
        return render(request,'assets/ipaddress.html',{'ipaddress':ipaddress})
    else:
        return render(request, 'assets/ipaddress.html')

@login_required(login_url='/login/')
def ipaddressdetail(request,ipaddress_id):
    if request.POST:
       ipaddress = get_object_or_404(models.IpAddress,id=ipaddress_id)
       oldipaddress = get_object_or_404(models.IpAddress,id=ipaddress_id)
       ipaddress.ipaddress_status=request.POST['ipaddress_status']
       ipaddress.ipaddress_customer=request.POST['ipaddress_customer']
       ipaddress.memo=request.POST['memo']
       if request.POST['asset']:
          try:
             asset = get_object_or_404(models.Asset,name=request.POST['asset'])
          except:
             messages.error(request,"分配设备不存在，请确认设备固资编号")
             return HttpResponseRedirect('/ipaddressdetail/%s' %ipaddress_id)
          else:
             models.IpAddress.objects.filter(id=ipaddress_id).update(asset=asset)
             ipaddress.asset = asset
       else:
           ipaddress.asset = None
       ipaddress.save()
       detaillist=[]
       ipaddress_new = get_object_or_404(models.IpAddress,id=ipaddress_id)
       if oldipaddress.asset != ipaddress_new.asset:
          change = '分配设备由“%s”修改为“%s”' %(oldipaddress.asset,ipaddress_new.asset)
          detaillist.append(change)
       if oldipaddress.ipaddress_status != ipaddress_new.ipaddress_status:
          change = '状态由“%s”修改为“%s”' %(oldipaddress.get_ipaddress_status_display(),ipaddress_new.get_ipaddress_status_display())
          detaillist.append(change)
       if oldipaddress.ipaddress_customer != ipaddress_new.ipaddress_customer:
          change = '客户设备由“%s”修改为“%s”' %(oldipaddress.ipaddress_customer,ipaddress_new.ipaddress_customer)
          detaillist.append(change)
       if oldipaddress.memo != ipaddress_new.memo:
          change = '客户设备由“%s”修改为“%s”' %(oldipaddress.memo,ipaddress_new.memo)
          detaillist.append(change)
       detail = '; '.join(detaillist)
       if detail:
          ipeventlog = models.IpEventLog(ipaddress=ipaddress_new,event_type=1,reason=request.POST['reason'],detail=detail,user=request.user)
          ipeventlog.save()
          return HttpResponseRedirect('/ipaddressdetail/%s' %ipaddress_id)
       else:
          messages.error(request,"数据无变化")
          return HttpResponseRedirect('/ipaddressdetail/%s' %ipaddress_id)
    else:
       ipeventlog = models.IpEventLog.objects.filter(ipaddress_id=ipaddress_id)
       ipaddress = get_object_or_404(models.IpAddress,id=ipaddress_id)
       return render(request, 'assets/ipaddressdetail.html',{'ipaddress':ipaddress,'ipeventlog':ipeventlog})

@login_required(login_url='/login/')
def cabinetdetail(request,cabinet_id):
    if request.POST:
       cabinet = get_object_or_404(models.Cabinet, id=cabinet_id)
       oldcabinet = get_object_or_404(models.Cabinet, id=cabinet_id)
       detaillist=[]
       name = request.POST['name']
       machineroom = request.POST['machineroom']
       cabinet.slotcount=request.POST['slotcount']
       cabinet.status = request.POST['status']
       cabinet.power = request.POST['power']
       cabinet.memo = request.POST['memo']
       cabinet.user=request.POST['user']
       if name:
           if machineroom:
               try:
                   tempmachineroom = get_object_or_404(models.MachineRoom,name=machineroom)
               except:
                   messages.error(request,"机房管理单元:%s不存在" %machineroom)
                   return HttpResponseRedirect('/cabinetdetail/%s' %cabinet_id)
               else:
                   try:
                      tempcabinet = get_object_or_404(models.Cabinet,name=name,machineroom=tempmachineroom)
                   except:
                      cabinet.name = name
                   else:
                      if cabinet != tempcabinet:
                          messages.error(request,"机房管理单元:%s已经存在机架:%s" %(machineroom,name))
                          return HttpResponseRedirect('/cabinetdetail/%s' %cabinet_id)
                      else:
                          cabinet.name = name
                          cabinet.machineroom = tempmachineroom
           else:
               messages.error(request,"机房管理单元不能为空")
               return HttpResponseRedirect('/cabinetdetail/%s' %cabinet_id)
       else:
           messages.error(request,"机架名不能为空")
           return HttpResponseRedirect('/cabinetdetail/%s' %cabinet_id)   
       cabinet.save()
       newcabinet = get_object_or_404(models.Cabinet, id=cabinet_id)
       if oldcabinet.name != newcabinet.name:
           change = '机柜名称由:“%s”修改为“%s”' %(oldcabinet.name,newcabinet.name)
           detaillist.append(change)
       if oldcabinet.machineroom != newcabinet.machineroom:
           change = '机柜管理单元由:“%s”修改为“%s”' %(oldcabinet.machineroom,newcabinet.machineroom)
           detaillist.append(change) 
       if oldcabinet.slotcount != newcabinet.slotcount:
          change = '机柜高度由“%sU”修改为“%sU”' %(oldcabinet.slotcount,newcabinet.slotcount)
          detaillist.append(change)
       if oldcabinet.user != newcabinet.user:
          change = '机柜是否自用由“%s”修改为“%s”' %(oldcabinet.get_user_display(),newcabinet.get_user_display())
          detaillist.append(change)
       if oldcabinet.status != newcabinet.status:
          change = '机柜开电状态由“%s”修改为“%s”' %(oldcabinet.get_status_display(),newcabinet.get_status_display())
          detaillist.append(change)
       if oldcabinet.power != newcabinet.power:
          change = '机柜电力由“%sA”修改为“%sA”' %(oldcabinet.power,newcabinet.power) 
          detaillist.append(change)
       if oldcabinet.memo != newcabinet.memo:
          change = '备注由“%s”修改为“%s”' %(oldcabinet.memo,newcabinet.memo) 
          detaillist.append(change)
       detail = '; '.join(detaillist)
       if detail:
          eventlog = models.EventLog(cabinet=cabinet,event_type=1,reason=request.POST['reason'],detail=detail,user=request.user)
          eventlog.save()
          return HttpResponseRedirect('/cabinetdetail/%s' %cabinet_id)
       else:
          messages.error(request,"数据无变化")
          return HttpResponseRedirect('/cabinetdetail/%s' %cabinet_id)
    else:
       datacenter = models.DataCenter.objects.all()
       cabinet = get_object_or_404(models.Cabinet, id=cabinet_id)
       machineroom = models.MachineRoom.objects.filter(datacenter=cabinet.datacenter)
       asset =  models.Asset.objects.filter(cabinet_id=cabinet_id)
       eventlog = models.EventLog.objects.filter(cabinet_id=cabinet_id)
       return render(request, 'assets/cabinetdetail.html',{'cabinet':cabinet,'asset':asset,'eventlog':eventlog,'datacenter':datacenter,'machineroom':machineroom}) 

@login_required(login_url='/login/')
def serverdetail(request, asset_id):
    """
    服务器
    """
    asset = get_object_or_404(models.Asset, id=asset_id)
    if asset.asset_type == 'server':
        if request.POST:
            detaillist=[]
            oldasset = models.Asset.objects.get(id=asset_id)
            asset = models.Asset.objects.get(id=asset_id)
            asset.business_unit = request.POST['business_unit']
            asset.status = request.POST['status']
            asset.high = request.POST['high']
            asset.application = request.POST['application']
            asset.memo = request.POST['memo']
            sn = request.POST['sn']
            manufacturer = request.POST['manufacturer']
            modelnumber = request.POST['modelnumber']
            idc = request.POST['idc']
            machineRoom = request.POST['machineRoom']
            cabinet = request.POST['cabinet']            
            manage_ip = request.POST['manage_ip']            
            operation = request.POST['operation']            
            reason = request.POST['reason']
            if sn:
                try:
                    tempserver = get_object_or_404(models.Asset,sn=sn)
                except:
                    asset.sn=sn
                else:
                    if tempserver != asset:
                       messages.error(request,'修改失败,SN%s已存在' %sn)
                       return HttpResponseRedirect('/serverdetail/%s' %asset_id)
            else:
                messages.error(request,'修改失败,SN不能为空')
                return HttpResponseRedirect('/serverdetail/%s' %asset_id) 
            if idc:
                try:
                    idc_name = models.DataCenter.objects.get(name=idc)
                except:
                    messages.error(request,'修改失败,机房不存在')
                    return HttpResponseRedirect('/serverdetail/%s' %asset_id)
                else:
                    asset.idc = idc_name
            else:
                asset.idc = None            
            if machineRoom:
                try:
                    machineRoom_name = models.MachineRoom.objects.get(name=machineRoom)
                except:
                    messages.error(request,'修改失败,机房管理单元不存在')
                    return HttpResponseRedirect('/serverdetail/%s' %asset_id)
                else:
                    asset.machineRoom = machineRoom_name
            else:
                asset.machineRoom = None        
            if cabinet:
                if machineRoom:
                   try:
                      cabinet_name = models.Cabinet.objects.get(name=cabinet,machineroom = machineRoom_name)
                   except:
                      messages.error(request,'修改失败,机房管理单元无该机架%s' %cabinet)
                      return HttpResponseRedirect('/serverdetail/%s' %asset_id)
                   else:
                      asset.cabinet = cabinet_name
                else:
                    messages.error(request,'修改失败,机房管理单元为空时，机架需要为空')
                    return HttpResponseRedirect('/serverdetail/%s' %asset_id)
            else:
                asset.cabinet = None        
            if modelnumber:
                try:
                    modelnumber_name = models.Modelnumber.objects.get(name=modelnumber)
                except:
                    messages.error(request,'修改失败,型号%s不存在' %modelnumber)
                    return HttpResponseRedirect('/serverdetail/%s' %asset_id)
                else:
                    asset.modelnumber = modelnumber_name
            else:
                asset.modelnumber = None        
            if manufacturer:
                try:
                    manufacturer_name = models.Manufacturer.objects.get(name=manufacturer)
                except:
                    messages.error(request,'修改失败,厂商%s不存在' %manufacturer)
                    return HttpResponseRedirect('/serverdetail/%s' %asset_id)
                else:
                    asset.manufacturer = manufacturer_name
            else:
                asset.manufacturer = None        
            if operation:
                try:
                    operation_name = User.objects.get(username=operation)
                except:
                    messages.error(request,'修改失败,维护人%s不存在' %operation)
                    return HttpResponseRedirect('/serverdetail/%s' %asset_id)
                else:
                    asset.operation = operation_name
            else:
                asset.operation = None
            if manage_ip:
                asset.manage_ip = manage_ip
            else:
                asset.manage_ip = None           
            asset.save() 
            asset = models.Asset.objects.get(id=asset_id)
            if oldasset.sn != asset.sn:
               snchange = 'SN由“%s”修改为“%s”' %(oldasset.sn,asset.sn) 
               detaillist.append(snchange)
            if oldasset.business_unit != asset.business_unit:
               business_unitchange = '业务线由“' + oldasset.get_business_unit_display() + '”修改为“' + asset.get_business_unit_display() + '”'
               detaillist.append(business_unitchange)
            if oldasset.manufacturer != asset.manufacturer:
               manufacturerchange = '厂商由“' + str(oldasset.manufacturer) + '”修改为“' + str(asset.manufacturer) + '”'
               detaillist.append(manufacturerchange)
            if oldasset.modelnumber != asset.modelnumber:
               modelnumberchange = '型号由“' + (oldasset.modelnumber) + '”修改为“' + str(asset.modelnumber) + '”'
               detaillist.append(modelnumberchange)
            if oldasset.status != asset.status:
               statuschange = '状态由“' +oldasset.get_status_display() + '”修改为“' + asset.get_status_display() + '”'
               detaillist.append(statuschange)
            if oldasset.idc != asset.idc:
               idcchange = '机房由“' + str(oldasset.idc) + '”修改为“' + str(asset.idc) + '”'
               detaillist.append(idcchange)
            if oldasset.machineRoom != asset.machineRoom:
               machineRoomchange = '机房单元由“' + str(oldasset.machineRoom) + '”修改为“' + str(asset.machineRoom) + '”'
               detaillist.append(machineRoomchange)
            if oldasset.cabinet != asset.cabinet:
               cabinetchange = '机架由“' + str(oldasset.cabinet)  + '”修改为“' + str(asset.cabinet) + '”'
               detaillist.append(cabinetchange)
            if oldasset.high != asset.high:
               highchange = '设备高度由“' +str(oldasset.high) + '”修改为“' + str(asset.high) + '”'
               detaillist.append(highchange)
            if oldasset.manage_ip != asset.manage_ip:
               manage_ipchange = '管理IP由“' + str(oldasset.manage_ip) + '”修改为“' + str(asset.manage_ip) + '”'
               detaillist.append(manage_ipchange)
            if oldasset.application != asset.application:
               applicationchange = '应用由“' +str(oldasset.application) + '”修改为“' + str(asset.application) + '”'
               detaillist.append(applicationchange)
            if oldasset.operation != asset.operation:
               operationchange = '维护人由“' +str(oldasset.operation) + '”修改为“' + str(asset.operation) + '”'
               detaillist.append(operationchange)
            if oldasset.memo != asset.memo:
               memochange = '备注由“' + str(oldasset.memo) + '”修改为“' + str(asset.memo) + '”'
               detaillist.append(memochange)
            detail = '; '.join(detaillist)
            if detail:
               eventlog = models.EventLog(asset=asset,event_type=1,reason=reason,detail=detail,user=request.user)
               eventlog.save()
               eventlog = models.EventLog.objects.filter(asset=asset_id)
               server = get_object_or_404(models.Server,asset_id=asset_id)
               return HttpResponseRedirect('/serverdetail/%s' %asset_id)
            else:
               return HttpResponse("无数据变化")
        else:
            datacenter = models.DataCenter.objects.all()
            machineroom = models.MachineRoom.objects.filter(datacenter=asset.idc)
            eventlog = models.EventLog.objects.filter(asset=asset_id)
            server = get_object_or_404(models.Server,asset_id=asset_id)
            port = models.Ports.objects.filter(connect_server__asset_id=asset_id)
            ipaddress = models.IpAddress.objects.filter(asset_id=asset_id)
            #return render(request, 'assets/serverdetail.html', { 'asset':asset,'eventlog':eventlog,'server':server,'port':port,'ipaddress':ipaddress,'datacenter':datacenter} )
            return render(request, 'assets/serverdetail.html',locals())

@login_required(login_url='/login/')
def networkdevicedetail(request, asset_id):
    asset = get_object_or_404(models.Asset, id=asset_id)
    if asset.asset_type == 'networkdevice':
        networkdevice = get_object_or_404(models.NetworkDevice,asset_id=asset_id)
        if request.POST:
            detaillist=[]
            if request.POST.get('submit') == 'port_add':
                port = models.Ports()
                asset = get_object_or_404(models.Asset,id=asset_id)
                port.name = request.POST['name']
                port.port_type = request.POST['port_type']
                port.port_status = request.POST['port_status']
                #connect_port_text = request.POST['connect_port']
                #connect_networkdevicetext = request.POST['connect_networkdevice']
                port.connect_user = request.POST['connect_user']
                if port.name == '':
                   messages.error(request,'设备端口不能为空')
                   return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                else:
                   try:
                      tempport = models.Ports.objects.get(name=port.name,networkdevice=asset)
                   except:
                      port.networkdevice = asset
                      port.save()
                      return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                   else:
                      messages.error(request,'端口已经存在')
                      return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
            elif request.POST.get('submit') == 'port_edit':
                name = request.POST['name']
                port = models.Ports.objects.get(name=name,networkdevice_id=asset_id)
                port.port_type = request.POST['port_type']
                port.port_status = request.POST['port_status']
                port.connect_user = request.POST['connect_user']
                #connect_porttext = request.POST['connect_port']
                #connect_networkdevice = request.POST['connect_networkdevice']
                #connect_server = request.POST['connect_server']
                port.save()
                return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)                                
            elif request.POST.get('submit') == 'port_del':
                name = request.POST['name']
                networkdeviceitem = models.Asset.objects.get(id=asset_id)
                port = models.Ports.objects.get(name=name,networkdevice=networkdeviceitem)
                if (port.connect_port or port.connect_server):
                   messages.error(request,'端口存在链接关系，无法删除')
                   return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                else:
                   port.delete()
                   return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
            elif request.POST.get('submit') == 'portbatchdel':
                portbatchdel = request.POST['portbatchdel']
                portlist = portbatchdel.split(',')
                for key in portlist:
                    port = models.Ports.objects.get(name=key,networkdevice_id=asset_id)
                    if (port.connect_port or port.connect_server):
                        messages.error(request,'端口:%s存在链接关系，无法删除' %key)
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    else:
                        port.delete()
                return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
            elif request.POST.get('submit') == 'portconnectdel':
                portconnectdel = request.POST['portconnectdel']
                portlist = portconnectdel.split(',')
                for key in portlist:
                    port = models.Ports.objects.get(name=key,networkdevice_id=asset_id)
                    if not (port.connect_port or port.connect_server):
                        messages.error(request,'端口%s无链接关系，无法删除' %key)
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    elif port.connect_port:
                        connect_port = models.Ports.objects.get(connect_port=port)
                        port.connect_port = None
                        connect_port.connect_port = None
                        port.save()
                        connect_port.save()
                    else:
                        port.connect_server = None
                        port.save()       
                return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
            elif request.POST.get('submit') == 'networkdevice_edit':
                oldasset = get_object_or_404(models.Asset, id=asset_id)
                asset = get_object_or_404(models.Asset, id=asset_id)                
                asset.hostname = request.POST['hostname']
                asset.status = request.POST['status']
                asset.high = request.POST['high']
                asset.application = request.POST['application']
                asset.memo = request.POST['memo']
                business_unit = request.POST['business_unit']
                sn = request.POST['sn']
                manufacturer = request.POST['manufacturer']
                modelnumber = request.POST['modelnumber']                
                idc = request.POST['idc']
                machineRoom = request.POST['machineRoom']
                cabinet = request.POST['cabinet']                
                manage_ip = request.POST['manage_ip']                
                operation = request.POST['operation']                
                reason = request.POST['reason']
                if sn:
                    try:
                        tempnetworkdevice = get_object_or_404(models.Asset,sn=sn)
                    except:
                        asset.sn=sn
                    else:
                        if tempnetworkdevice != asset:
                           messages.error(request,'修改失败,SN%s已存在' %sn)
                           return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                else:
                    messages.error(request,'修改失败,SN不能为空')
                    return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id) 
                if idc:
                    try:
                        idc_name = models.DataCenter.objects.get(name=idc)
                    except:
                        messages.error(request,'修改失败,机房不存在')
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    else:
                        asset.idc = idc_name
                else:
                    asset.idc = None            
                if machineRoom:
                    try:
                        machineRoom_name = models.MachineRoom.objects.get(name=machineRoom)
                    except:
                        messages.error(request,'修改失败,机房管理单元不存在')
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    else:
                        asset.machineRoom = machineRoom_name
                else:
                    asset.machineRoom = None        
                if cabinet:
                    try:
                        cabinet_name = models.Cabinet.objects.get(name=cabinet,machineroom = machineRoom_name)
                    except:
                        messages.error(request,'修改失败,机房无该机架%s' %cabinet)
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    else:
                        asset.cabinet = cabinet_name
                else:
                    asset.cabinet = None        
                if modelnumber:
                    try:
                        modelnumber_name = models.Modelnumber.objects.get(name=modelnumber)
                    except:
                        messages.error(request,'修改失败,型号%s不存在' %modelnumber)
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    else:
                        asset.modelnumber = modelnumber_name
                else:
                    asset.modelnumber = None        
                if manufacturer:
                    try:
                        manufacturer_name = models.Manufacturer.objects.get(name=manufacturer)
                    except:
                        messages.error(request,'修改失败,厂商%s不存在' %manufacturer)
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    else:
                        asset.manufacturer = manufacturer_name
                else:
                    asset.manufacturer = None        
                if operation:
                    try:
                        operation_name = User.objects.get(username=operation)
                    except:
                        messages.error(request,'修改失败,维护人%s不存在' %operation)
                        return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                    else:
                        asset.operation = operation_name
                else:
                    asset.operation = None
                if manage_ip:
                    asset.manage_ip = manage_ip
                else:
                    asset.manage_ip = None
                asset.save()
                asset = get_object_or_404(models.Asset, id=asset_id)
                if oldasset.sn != asset.sn:
                    snchange= 'SN由“'+ str(oldasset.sn) + '”修改为“' + str(asset.sn) + '”'
                    detaillist.append(snchange)
                if oldasset.hostname != asset.hostname:
                    hostnamechange = 'Hostname由“' + str(oldasset.hostname) + '”修改为“' + str(asset.hostname) + '”'
                    detaillist.append(hostnamechange)    
                if oldasset.business_unit != asset.business_unit:
                    business_unitchange = '业务线由“' + oldasset.get_business_unit_display() + '”修改为“' + asset.get_business_unit_display() + '”'
                    detaillist.append(business_unitchange)
                if oldasset.manufacturer != asset.manufacturer:
                    manufacturerchange = '厂商由“' + str(oldasset.manufacturer) + '”修改为“' + str(asset.manufacturer) + '”'
                    detaillist.append(manufacturerchange)
                if oldasset.modelnumber != asset.modelnumber:
                    modelnumberchange = '型号由“' + str(oldasset.modelnumber) + '”修改为“' + str(asset.modelnumber) + '”'
                    detaillist.append(modelnumberchange)
                if oldasset.status != asset.status:
                    statuschange = '状态由“' +oldasset.get_status_display() + '”修改为“' + asset.get_status_display() + '”'
                    detaillist.append(statuschange)
                if oldasset.idc != asset.idc:
                    idcchange = '机房由“' + str(oldasset.idc) + '”修改为“' + str(asset.idc) + '”'
                    detaillist.append(idcchange)
                if oldasset.machineRoom != asset.machineRoom:
                    machineRoomchange = '机房单元由“' + str(oldasset.machineRoom) + '”修改为“' + str(asset.machineRoom) + '”'
                    detaillist.append(machineRoomchange)
                if oldasset.cabinet != asset.cabinet:
                    cabinetchange = '机架由“' + str(oldasset.cabinet)  + '”修改为“' + str(asset.cabinet) + '”'
                    detaillist.append(cabinetchange)
                if oldasset.high != asset.high:
                    highchange = '设备高度由“' +str(oldasset.high) + '”修改为“' + str(asset.high) + '”'
                    detaillist.append(highchange)
                if oldasset.manage_ip != asset.manage_ip:
                    manage_ipchange = '管理IP由“' + str(oldasset.manage_ip) + '”修改为“' + str(asset.manage_ip) + '”'
                    detaillist.append(manage_ipchange)
                if oldasset.application != asset.application:
                    applicationchange = '应用由“' +str(oldasset.application) + '”修改为“' + str(asset.application) + '”'
                    detaillist.append(applicationchange)
                if oldasset.operation != asset.operation:
                    operationchange = '维护人由“' +str(oldasset.operation) + '”修改为“' + str(asset.operation) + '”'
                    detaillist.append(operationchange)
                if oldasset.memo != asset.memo:
                    memochange = '备注由“' + str(oldasset.memo) + '”修改为“' + str(asset.memo) + '”'
                    detaillist.append(memochange)
                detail = '; '.join(detaillist)
                if detail:
                    eventlog = models.EventLog(asset=asset,event_type=1,reason=reason,detail=detail,user=request.user)
                    eventlog.save()
                    ports = models.Ports.objects.filter(networkdevice=asset_id)
                    eventlog = models.EventLog.objects.filter(asset=asset_id)
                    return HttpResponseRedirect('/networkdevicedetail/%s' %asset_id)
                else:
                    return HttpResponse("无数据变化")
        else:
            datacenter = models.DataCenter.objects.all()
            machineroom = models.MachineRoom.objects.filter(datacenter=asset.idc)
            ports = models.Ports.objects.filter(networkdevice=asset_id)
            eventlog = models.EventLog.objects.filter(asset=asset_id)
            #return render(request, 'assets/networkdevicedetail.html', {'networkdevice':networkdevice,'asset':asset,'ports':ports,'eventlog':eventlog})
            return render(request, 'assets/networkdevicedetail.html',locals())


@login_required(login_url='/login/')
def datacenterdetail(request,datacenter_id,machineroom_id=0):
    """
    数据中心
    """
    if request.POST:
        datacenter = get_object_or_404(models.DataCenter, id=datacenter_id)
        detaillist=[]
        if request.POST.get('submit') == 'datacenter_edit':
            name = request.POST['name']
            shortname = request.POST['shortname']
            isp = request.POST['isp']
            admin = request.POST['admin']
            contactnumber = request.POST['contactnumber']
            address = request.POST['address']
            reason = request.POST['reason']
            memo = request.POST['memo']
            if admin:
               try:
                  admin_name = User.objects.get(username=request.POST['admin'])
               except:
                  messages.error(request,"维护人用户名%s不存在" %admin)
                  return HttpResponseRedirect('/datacenterdetail/%s' %datacenter_id)
               else:
                  models.DataCenter.objects.filter(id=datacenter_id).update(admin=admin_name)
            else:
               models.DataCenter.objects.filter(id=datacenter_id).update(admin=None)
            models.DataCenter.objects.filter(id=datacenter_id).update(name=name,shortname = shortname,isp = isp,contactnumber = contactnumber,address=address,memo=memo)
            newdatacenter = get_object_or_404(models.DataCenter, id=datacenter_id)
            if datacenter.shortname != newdatacenter.shortname:
               change = '数据中心简称由“%s”修改为“%s”' %(datacenter.shortname,newdatacenter.shortname)
               detaillist.append(change)       
            if datacenter.isp != newdatacenter.isp:
               change = '运营商由“%s”修改为“%s”' %(datacenter.isp,newdatacenter.isp)
               detaillist.append(change)
            if datacenter.admin != newdatacenter.admin:
               change = '维护人由“%s”修改为“%s”' %(datacenter.admin,newdatacenter.admin)
               detaillist.append(change)
            if datacenter.contactnumber != newdatacenter.contactnumber:
               change = '联系电话由“%s”修改为“%s”' %(datacenter.contactnumber,newdatacenter.contactnumber)
               detaillist.append(change)
            if datacenter.address != newdatacenter.address:
               change = '机房地址由“%s”修改为“%s”' %(datacenter.address,newdatacenter.address) 
               detaillist.append(change)
            if datacenter.memo != newdatacenter.memo:
               change = '备注由“%s”修改为“%s”' %(datacenter.memo,newdatacenter.memo) 
               detaillist.append(change)
            detail = '; '.join(detaillist)
            if detail:
               eventlog = models.EventLog(datacenter=datacenter,event_type=1,reason=request.POST['reason'],detail=detail,user=request.user)
               eventlog.save()
               return HttpResponseRedirect('/datacenterdetail/%s' %datacenter_id)
            else:
               return HttpResponse("无数据变化")
        elif request.POST.get('submit') == 'machineroom_add':
            name = request.POST['name']
            memo = request.POST['memo']
            admin_name = User.objects.get(username=request.POST['admin'])
            machineroom = models.MachineRoom(name=name,datacenter_id=datacenter_id,admin = admin_name,memo=memo)
            machineroom.save()
            detail = '新增机房管理单元名称：%s，维护人：%s，备注：%s' %(name,admin_name,memo)
            eventlog = models.EventLog(datacenter=datacenter,event_type=0,detail=detail,user=request.user)
            eventlog.save()
            return HttpResponseRedirect('/datacenterdetail/%s' %datacenter_id)
        elif request.POST.get('submit') == 'machineroom_edit':
            name = request.POST['name']
            admin = request.POST['admin']
            memo = request.POST['memo']
            admin_name = User.objects.get(username=admin)
            machineroom = get_object_or_404(models.MachineRoom,name=name)
            models.MachineRoom.objects.filter(name=name).update(datacenter_id=datacenter_id,admin = admin_name,memo=memo) 
            newmachineroom = get_object_or_404(models.MachineRoom,name=name)
            if machineroom.admin != newmachineroom.admin:
               change = '机房管理单元：%s的维护人由“%s”修改为“%s”' %(machineroom.name,machineroom.admin,newmachineroom.admin)
               detaillist.append(change)
            if machineroom.memo != newmachineroom.memo:
               change = '机房管理单元：%s的备注由“%s”修改为“%s”' %(machineroom.name,machineroom.memo,newmachineroom.memo)
               detaillist.append(change)
            detail = '; '.join(detaillist)
            if detail:
               eventlog = models.EventLog(datacenter=datacenter,event_type=1,reason=request.POST['reason'],detail=detail,user=request.user)
               eventlog.save()
               return HttpResponseRedirect('/datacenterdetail/%s' %datacenter_id)
            else:
               return HttpResponse("无数据变化")
        elif request.POST.get('submit') == 'machineroom_del':
            name = request.POST['name']
            models.MachineRoom.objects.filter(name=name,datacenter_id=datacenter_id).delete()
            detail = '删除机房管理单元：%s' %name
            eventlog = models.EventLog(datacenter=datacenter,event_type=2,reason=request.POST['reason'],detail=detail,user=request.user)
            eventlog.save()
            return HttpResponseRedirect('/datacenterdetail/%s' %datacenter_id)
    datacenter = get_object_or_404(models.DataCenter, id=datacenter_id)    
    machineroom = models.MachineRoom.objects.filter(datacenter_id=datacenter_id)
    cabinet = models.Cabinet.objects.filter(datacenter_id=datacenter_id)
    eventlog = models.EventLog.objects.filter(datacenter_id=datacenter_id)
    return render(request, 'assets/datacenterdetail.html', {'datacenter':datacenter,'machineroom':machineroom,'cabinet':cabinet,'eventlog':eventlog})


@login_required(login_url='/login/')
def networkdevice(request):
    if request.GET:
       name=request.GET['name']
       name_split = name.split()
       name_qlist = []
       for key in name_split:
           name_qlist.append(Q(name__icontains=key))
       if name_qlist:
          name_assets = models.Asset.objects.filter(reduce(operator.or_, name_qlist))
       else:
          name_assets = models.Asset.objects.all()
       sn=request.GET['sn']
       sn_split = sn.split()
       sn_qlist = []
       for key in sn_split:
           sn_qlist.append(Q(sn__icontains=key))
       if sn_qlist:
          sn_assets = models.Asset.objects.filter(reduce(operator.or_,sn_qlist))
       else:
          sn_assets = models.Asset.objects.all()
       hostname = request.GET['hostname']
       hostname_split = hostname.split()
       hostname_qlist = []
       for key in hostname_split:
           hostname_qlist.append(Q(hostname__icontains=key))
       if hostname_qlist:
           hostname_assets = models.Asset.objects.filter(reduce(operator.or_,hostname_qlist))
       else:
           hostname_assets = models.Asset.objects.all()
       idc=request.GET['idc']
       business_unit = request.GET['business_unit']
       cabinet = request.GET['cabinet']
       modelnumber = request.GET['modelnumber']
       manufacturer = request.GET['manufacturer']
       status = request.GET['status']
       manage_ip = request.GET['manage_ip']
       operation =request.GET['operation']
       qlist=[Q(business_unit__icontains=business_unit),Q(status__icontains=status),Q(asset_type='networkdevice')]
       if operation:
          qlist.append(Q(operation__username__icontains=operation))
       else:
          qlist.append(Q(operation__username__icontains=operation) | Q(operation__username__isnull=True))
       if cabinet:
          qlist.append(Q(cabinet__name__icontains=cabinet))
       else:
          qlist.append(Q(cabinet__name__icontains=cabinet) | Q(cabinet__name__isnull=True))
       if modelnumber:
          qlist.append(Q(modelnumber__name__icontains=modelnumber))
       else:
          qlist.append(Q(modelnumber__name__icontains=modelnumber) | Q(modelnumber__name__isnull=True))
       if manage_ip:
          qlist.append(Q(manage_ip__icontains=manage_ip))
       else:
          qlist.append(Q(manage_ip__icontains=manage_ip) | Q(manage_ip__isnull=True))
       if idc:
          qlist.append(Q(idc__name__icontains=idc))
       else:
          qlist.append(Q(idc__name__icontains=idc) | Q(idc__name__isnull=True))
       if manufacturer:
          qlist.append(Q(manufacturer__name__icontains=manufacturer))
       else:
          qlist.append(Q(manufacturer__name__icontains=manufacturer) | Q(manufacturer__name__isnull=True))
       other_assets = models.Asset.objects.filter(reduce(operator.and_, qlist))
       assets = other_assets & name_assets & sn_assets & hostname_assets
       return render(request, 'assets/networkdevice.html',{'assets':assets} )
    else:
       return render(request, 'assets/networkdevice.html')

@login_required(login_url='/login/')
def file_download(request,id=id):
    """
    导入模版下载
    """
    def file_iterator(file_name, chunk_size=512):
        with open(file_name,'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
    if id == '0':
       file_name = '/root/cmdb/assets/templates/download/server_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="server_import_template.xlsx"'
       return response
    elif id == '1':
       file_name = '/root/cmdb/assets/templates/download/networkdevice_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="networkdevice_import_template.xlsx"'
       return response
    elif id =='2':
       file_name = '/root/cmdb/assets/templates/download/cabinet_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="cabinet_import_template.xlsx"'
       return response
    elif id =='3':
       file_name = '/root/cmdb/assets/templates/download/datacenter_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="datacenter_import_template.xlsx"'
       return response
    elif id == '网段':
       file_name = '/root/cmdb/assets/templates/download/ipnet_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="ipnet_import_template.xlsx"'
       return response
    elif id =='5':
       file_name = '/root/cmdb/assets/templates/download/port_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="port_import_template.xlsx"'
       return response
    elif id =='6':
       file_name = '/root/cmdb/assets/templates/download/interconnect_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="interconnect_import_template.xlsx"'
       return response
    elif id == '专线':
       file_name = '/root/cmdb/assets/templates/download/circuit_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="circuit_import_template.xlsx"'
       return response
    elif id == 'DWDM':
       file_name = '/root/cmdb/assets/templates/download/dwdm_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="dwdm_import_template.xlsx"'
       return response
    elif id == '波道':
       file_name = '/root/cmdb/assets/templates/download/channel_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="channel_import_template.xlsx"'
       return response
    elif id == '互联网段':
       file_name = '/root/cmdb/assets/templates/download/conipnet_import_template.xlsx'
       response = StreamingHttpResponse(file_iterator(file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="conipnet_import_template.xlsx"'
       return response
    else:
       messages.success(request,"访问网页不存在，请检查输入网址")
       return HttpResponseRedirect('/file_download/%s' %id)

@login_required(login_url='/login/')
def circuit(request):
    if request.GET:
       name=request.GET['name']
       number=request.GET['number']
       business_unit = request.GET['business_unit']
       maintainer = request.GET['maintainer']
       status = request.GET['status']
       circuit_type = request.GET['circuit_type']
       isp = request.GET['isp']
       self_use_status = request.GET['self_use_status']
       name_split = name.split()
       name_qlist = []
       for key in name_split:
           name_qlist.append(Q(name__icontains=key))
       if name_qlist:
          name_circuit = models.Circuit.objects.filter(reduce(operator.or_, name_qlist))
       else:
          name_circuit = models.Circuit.objects.all()
       number_split = number.split()
       number_qlist = []
       for key in number_split:
           number_qlist.append(Q(number__icontains=key))
       if number_qlist:
          number_circuit = models.Circuit.objects.filter(reduce(operator.or_,number_qlist))
       else:
          number_circuit = models.Circuit.objects.all()   
       qlist=[Q(business_unit__icontains=business_unit),Q(status__icontains=status),Q(circuit_type__icontains=circuit_type),Q(isp__icontains=isp),Q(self_use_status__icontains=self_use_status)]
       if maintainer:
          qlist.append(Q(maintainer__username__icontains=maintainer))
       else:
          qlist.append(Q(maintainer__username__icontains=maintainer) | Q(maintainer__username__isnull=True))
       other_circuit = models.Circuit.objects.filter(reduce(operator.and_, qlist))
       circuit = other_circuit & name_circuit & number_circuit
       return render(request, 'assets/circuit.html',{'circuit':circuit} )
    else:
       return render(request, 'assets/circuit.html')


@login_required(login_url='/login/')
def circuitdetail(request, circuit_id):
    """
    专线信息
    """
    circuit = get_object_or_404(models.Circuit,id=circuit_id)
    if request.POST:
        oldcircuit = get_object_or_404(models.Circuit,id=circuit_id)
        detaillist=[]
        name = request.POST['name']
        number = request.POST['number']
        circuit.circuit_type = request.POST['circuit_type']
        circuit.bw = request.POST['bw'] if request.POST['bw'] else None
        circuit.status = request.POST['status']
        circuit.business_unit = request.POST['business_unit']
        circuit.self_use_status = request.POST['self_use_status']
        circuit.customer = request.POST['customer']
        maintainer = request.POST['maintainer']
        circuit.vlan = request.POST['vlan'] if request.POST['vlan'] else None
        circuit.isp = request.POST['isp']
        circuit.isp_contacts = request.POST['isp_contacts']
        circuit.isp_contacts_phonenumber = request.POST['isp_contacts_phonenumber']
        circuit.circuit_lenth = request.POST['circuit_lenth'] if request.POST['circuit_lenth'] else None
        circuit.attenuation = request.POST['attenuation'] if request.POST['attenuation'] else None
        circuit.date_online = request.POST['date_online'] if request.POST['date_online'] else None
        circuit.date_dismantle = request.POST['date_dismantle'] if request.POST['date_dismantle'] else None
        machineroom_a = request.POST['machineroom_a']
        cabinet_a = request.POST['cabinet_a']
        networkdevice_a= request.POST['networkdevice_a']
        port_a = request.POST['port_a']
        machineroom_z = request.POST['machineroom_z']
        cabinet_z = request.POST['cabinet_z']
        networkdevice_z = request.POST['networkdevice_z']
        port_z = request.POST['port_z']
        circuit.cloudnumber = request.POST['cloudnumber']
        dwdm = request.POST['dwdm']
        circuit.router = request.POST['router']
        circuit.memo = request.POST['memo']
        reason = request.POST['reason']
        if not name:
            messages.error(request,'修改失败,专线命名不能为空')
            return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
        if not number:
            messages.error(request,'修改失败,专线编号不能为空')
            return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
        try:
            tempcircuit = get_object_or_404(models.circuit,name=name)
        except:
            circuit.name = name
        else:
            if circuit != tempcircuit:
                messages.error(request,'修改失败,已存在专线命名为%s的专线' %name)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id) 
        try:
            tempcircuit = get_object_or_404(models.circuit,number=number)
        except:
                circuit.number = number
        else:
            if circuit != tempcircuit:
                messages.error(request,'修改失败,已存在专线编号为%s的专线' %number)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
        if maintainer:
            try:
                tempmaintainer = User.objects.get(username=maintainer)
            except:
                messages.error(request,'修改失败,维护人%s不存在' %maintainer)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
            else:
                circuit.maintainer = tempmaintainer
        else:
                circuit.maintainer = None
        if  machineroom_a:
            try:
                tempmachineroom_a = get_object_or_404(models.MachineRoom,name=machineroom_a)
            except:
                messages.error(request,'修改失败,起始端机房%s不存在' %machineroom_a)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id) 
            else:
                circuit.machineroom_a = tempmachineroom_a
        else:
            circuit.machineroom_a = None        
        if  cabinet_a:
            try:
                tempcabinet_a = get_object_or_404(models.Cabinet,name=cabinet_a)
            except:
                messages.error(request,'修改失败,起始端机柜%s不存在' %cabinet_a)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
            else:
                circuit.cabinet_a = tempcabinet_a
        else:
            circuit.cabinet_a = None 
        if  networkdevice_a:
            try:
                tempnetworkdevice_a = get_object_or_404(models.Asset,hostname=networkdevice_a)
            except:
                messages.error(request,'修改失败,起始端设备%s不存在' %networkdevice_a)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
            else:
                circuit.networkdevice_a = tempnetworkdevice_a
        else:
            circuit.networkdevice_a = None
        if  port_a:
            if tempnetworkdevice_a:
                try:
                    tempport_a = get_object_or_404(models.Ports,name=port_a,networkdevice=tempnetworkdevice_a)
                except:
                    messages.error(request,'修改失败,起始端设备%s不存在端口%s' %(networkdevice_a,port_a))
                    return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
                else:
                    circuit.port_a = tempport_a
            else:
                messages.error(request,'修改失败，只有端口，没有设备')
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
        else:
            circuit.port = None
        if  machineroom_z:
            try:
                tempmachineroom_z = get_object_or_404(models.MachineRoom,name=machineroom_z)
            except:
                messages.error(request,'修改失败,终止端机房%s不存在' %machineroom_z)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id) 
            else:
                circuit.machineroom_z = tempmachineroom_z
        else:
            circuit.machineroom_z = None        
        if  cabinet_z:
            try:
                tempcabinet_z = get_object_or_404(models.Cabinet,name=cabinet_z)
            except:
                messages.error(request,'修改失败,终止端机柜%s不存在' %cabinet_z)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
            else:
                circuit.cabinet_z = tempcabinet_z
        else:
            circuit.cabinet_z = None 
        if  networkdevice_z:
            try:
                tempnetworkdevice_z = get_object_or_404(models.Asset,hostname=networkdevice_z)
            except:
                messages.error(request,'修改失败,终止端设备%s不存在' %networkdevice_z)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
            else:
                circuit.networkdevice_z = tempnetworkdevice_z
        else:
            circuit.networkdevice_z = None
        if  port_z:
            if tempnetworkdevice_z:
                try:
                    tempport_z = get_object_or_404(models.Ports,name=port_z,networkdevice=tempnetworkdevice_z)
                except:
                    messages.error(request,'修改失败,终止端设备%s不存在端口%s' %(networkdevice_z,port_z))
                    return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
                else:
                    circuit.port_z = tempport_z
            else:
                messages.error(request,'修改失败,终止端只有端口，没有设备' %i)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
        else:
            circuit.port = None
        if  dwdm:
            try:
                tempdwdm = get_object_or_404(models.DWDM,name=dwdm)
            except:
                messages.error(request,'修改失败,DWDM名称为%s不存在' %dwdm)
                return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
            else:
                circuit.dwdm = tempdwdm
        else:
            circuit.dwdm = None
        circuit.save()
        circuit = get_object_or_404(models.Circuit,id=circuit_id)
        if oldcircuit.name != circuit.name:
            change = '专线名称由:“%s”修改为:“%s”' %(oldcircuit.name,circuit.name)
            detaillist.append(change)
        if oldcircuit.number != circuit.number:
            change = '专线编号由:“%s”修改为:“%s”' %(oldcircuit.number,circuit.number)
            detaillist.append(change) 
        if oldcircuit.circuit_type != circuit.circuit_type:
            change = '专线类型由:“%s”修改为:“%s”' %(oldcircuit.get_circuit_type_display(),circuit.get_circuit_type_display())
            detaillist.append(change)  
        if oldcircuit.bw != circuit.bw:
            change = '专线带宽由:“%d”修改为:“%d”' %(oldcircuit.bw,circuit.bw)
            detaillist.append(change)
        if oldcircuit.status != circuit.status:
            change = '专线状态由:“%s”修改为:“%s”' %(oldcircuit.get_status_display(),circuit.get_status_display())
            detaillist.append(change)
        if oldcircuit.business_unit != circuit.business_unit:
            change = '专线业务线由:“%s”修改为:“%s”' %(oldcircuit.get_business_unit_display(),circuit.get_business_unit_display())
            detaillist.append(change)
        if oldcircuit.self_use_status != circuit.self_use_status:
            change = '专线自用状态由:“%s”修改为:“%s”' %(oldcircuit.get_self_use_status_display(),circuit.get_self_use_status_display())
            detaillist.append(change)
        if oldcircuit.customer != circuit.customer:
            change = '专线客户由:“%s”修改为:“%s”' %(oldcircuit.customer,circuit.customer)
            detaillist.append(change)
        if oldcircuit.maintainer != circuit.maintainer:
            change = '专线维护人由:“%s”修改为:“%s”' %(oldcircuit.maintainer,circuit.maintainer)
            detaillist.append(change)
        if oldcircuit.vlan != circuit.vlan:
            change = '专线vlan由:“%s”修改为:“%s”' %(oldcircuit.vlan,circuit.vlan)
            detaillist.append(change)
        if oldcircuit.isp != circuit.isp:
            change = '专线运营商由:“%s”修改为:“%s”' %(oldcircuit.isp,circuit.isp)
            detaillist.append(change)
        if oldcircuit.isp_contacts != circuit.isp_contacts:
            change = '专线运营商联系人由:“%s”修改为:“%s”' %(oldcircuit.isp_contacts,circuit.isp_contacts)
            detaillist.append(change)
        if oldcircuit.isp_contacts_phonenumber != circuit.isp_contacts_phonenumber:
            change = '专线运营商联系电话由:“%s”修改为:“%s”' %(oldcircuit.isp_contacts_phonenumber,circuit.isp_contacts_phonenumber)
            detaillist.append(change)
        if oldcircuit.circuit_lenth != circuit.circuit_lenth:
            change = '裸光纤长度由:“%s”修改为:“%s”' %(oldcircuit.circuit_lenth,circuit.circuit_lenth)
            detaillist.append(change)
        if oldcircuit.attenuation != circuit.attenuation:
            change = '裸纤光衰由:“%s”修改为:“%s”' %(oldcircuit.attenuation,circuit.attenuation)
            detaillist.append(change)
        if oldcircuit.date_online != circuit.date_online:
            change = '专线启用日期由:“%s”修改为:“%s”' %(oldcircuit.date_online,circuit.date_online)
            detaillist.append(change)
        if oldcircuit.date_dismantle != circuit.date_dismantle:
            change = '专线拆除日期由:“%s”修改为:“%s”' %(oldcircuit.date_dismantle,circuit.date_dismantle)
            detaillist.append(change)
        if oldcircuit.machineroom_a != circuit.machineroom_a:
            change = '专线起始端机房单元由:“%s”修改为:“%s”' %(oldcircuit.machineroom_a,circuit.machineroom_a)
            detaillist.append(change)
        if oldcircuit.cabinet_a != circuit.cabinet_a:
            change = '专线起始端机架由:“%s”修改为:“%s”' %(oldcircuit.cabinet_a,circuit.cabinet_a)
            detaillist.append(change)                                                               
        if oldcircuit.networkdevice_a != circuit.networkdevice_a:
            try:
               oldnetworkdevice = get_object_or_404(models.Asset,id=oldcircuit.networkdevice_a_id)
            except:
               oldhostname = ''
            else:
               oldhostname = oldnetworkdevice.hostname
            try:
               networkdevice = get_object_or_404(models.Asset,id=circuit.networkdevice_a_id)
            except:
               hostname = ''
            else:
               hostname = networkdevice.hostname
            change = '专线起始端网络设备由:“%s”修改为:“%s”' %(oldhostname,hostname)
            detaillist.append(change)                                                               
        if oldcircuit.port_a != circuit.port_a:
            change = '专线起始端设备端口由:“%s”修改为:“%s”' %(oldcircuit.port_a,circuit.port_a)
            detaillist.append(change)                                                               
        if oldcircuit.machineroom_z != circuit.machineroom_z:
            change = '专线终止端机房单元由:“%s”修改为:“%s”' %(oldcircuit.machineroom_z,circuit.machineroom_z)
            detaillist.append(change)                                                               
        if oldcircuit.cabinet_z != circuit.cabinet_z:
            change = '专线终止端机架由:“%s”修改为:“%s”' %(oldcircuit.cabinet_z,circuit.cabinet_z)
            detaillist.append(change)                                                               
        if oldcircuit.networkdevice_z != circuit.networkdevice_z:
            try:
               oldnetworkdevice = get_object_or_404(models.Asset,id=oldcircuit.networkdevice_z_id)
            except:
               oldhostname = ''
            else:
               oldhostname = oldnetworkdevice.hostname
            try:
               networkdevice = get_object_or_404(models.Asset,id=circuit.networkdevice_z_id)
            except:
               hostname = ''
            else:
               hostname = networkdevice.hostname
            change = '专线终止端网络设备由:“%s”修改为:“%s”' %(oldhostname,hostname)
            detaillist.append(change)                                                               
        if oldcircuit.port_z != circuit.port_z:
            change = '专线终止端端口由:“%s”修改为:“%s”' %(oldcircuit.port_z,circuit.port_z)
            detaillist.append(change)                                                               
        if oldcircuit.cloudnumber != circuit.cloudnumber:
            change = '专线云专线编号由:“%s”修改为:“%s”' %(oldcircuit.cloudnumber,circuit.cloudnumber)
            detaillist.append(change) 
        if oldcircuit.dwdm != circuit.dwdm:
            change = '专线关联DWDM由:“%s”修改为:“%s”' %(oldcircuit.dwdm,circuit.dwdm)
            detaillist.append(change)
        if oldcircuit.router != circuit.router:
            change = '专线路由由:“%s”修改为:“%s”' %(oldcircuit.router,circuit.router)
            detaillist.append(change)
        if oldcircuit.memo != circuit.memo:
            change = '专线备注由:“%s”修改为:“%s”' %(oldcircuit.memo,circuit.memo)
            detaillist.append(change)
        detail = '; '.join(detaillist)
        if detail:
           eventlog = models.CircuitEventLog(circuit=circuit,event_type=1,reason=reason,detail=detail,user=request.user)
           eventlog.save()                                                                         
           return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
        else:
           messages.error(request,"无数据变化")
           return HttpResponseRedirect('/circuitdetail/%s' %circuit_id)
    else:
        eventlog = models.CircuitEventLog.objects.filter(circuit=circuit_id)
        machineroom = models.MachineRoom.objects.all()
        return render(request, 'assets/circuitdetail.html',{'circuit':circuit,'eventlog':eventlog,'machineroom':machineroom})

@login_required(login_url='/login/')
def dwdm(request):
    if request.GET:
        name=request.GET['name']
        manufacturer=request.GET['manufacturer']
        modelnumber = request.GET['modelnumber']
        business_unit = request.GET['business_unit']
        maintainer = request.GET['maintainer']
        status = request.GET['status']
        oeo = request.GET['oeo']
        olp = request.GET['olp']
        machineroom_a = request.GET['machineroom_a']
        machineroom_z = request.GET['machineroom_z']
        name_split = name.split()
        name_qlist = []
        for key in name_split:
            name_qlist.append(Q(name__icontains=key))
        if name_qlist:
            name_dwdm = models.DWDM.objects.filter(reduce(operator.or_, name_qlist))
        else:
           name_dwdm = models.DWDM.objects.all()
        qlist=[Q(business_unit__icontains=business_unit),Q(status__icontains=status),Q(oeo__icontains=oeo),Q(olp__icontains=olp)]
        if manufacturer:
            qlist.append(Q(manufacturer__name__icontains=manufacturer))
        else:
            qlist.append(Q(manufacturer__name__icontains=manufacturer) | Q(manufacturer__name__isnull=True))
        if modelnumber:
            qlist.append(Q(modelnumber__name__icontains=modelnumber))
        else:
            qlist.append(Q(modelnumber__name__icontains=modelnumber) | Q(modelnumber__name__isnull=True))
        if maintainer:
            qlist.append(Q(maintainer__username__icontains=maintainer))
        else:
            qlist.append(Q(maintainer__username__icontains=maintainer) | Q(maintainer__username__isnull=True))
        if machineroom_a:
            qlist.append(Q(machineroom_a__name__icontains=machineroom_a))
        else:
            qlist.append(Q(machineroom_a__name__icontains=machineroom_a) | Q(machineroom_a__name__isnull=True))
        if machineroom_z:
            qlist.append(Q(machineroom_z__name__icontains=machineroom_z))
        else:
            qlist.append(Q(machineroom_z__name__icontains=machineroom_z) | Q(machineroom_a__name__isnull=True))     
        other_dwdm = models.DWDM.objects.filter(reduce(operator.and_, qlist))
        dwdm = other_dwdm & name_dwdm
        return render(request, 'assets/dwdm.html',{'dwdm':dwdm} )
    else:
       return render(request, 'assets/dwdm.html')


@login_required(login_url='/login/')
def dwdmdetail(request,dwdm_id):
    """
    DWDM
    """
    dwdm = get_object_or_404(models.DWDM,id=dwdm_id)
    if request.POST:
        olddwdm = get_object_or_404(models.DWDM,id=dwdm_id)
        detaillist=[]
        name=request.POST['name']
        manufacturer=request.POST['manufacturer']
        modelnumber = request.POST['modelnumber']
        dwdm.status = request.POST['status']
        dwdm.business_unit = request.POST['business_unit']
        dwdm.high = request.POST['high'] if request.POST['high'] else None
        dwdm.mux = request.POST['mux']
        dwdm.oeo = request.POST['oeo']
        dwdm.olp = request.POST['olp']
        dwdm.ba = request.POST['ba']
        dwdm.pa = request.POST['pa']
        dwdm.dcm = request.POST['dcm']
        maintainer = request.POST['maintainer']
        machineroom_a = request.POST['machineroom_a']
        machineroom_z = request.POST['machineroom_z']
        cabinet_a = request.POST['cabinet_a']
        cabinet_z = request.POST['cabinet_z']
        device_a_number = request.POST['device_a_number']
        device_z_number = request.POST['device_z_number']
        dwdm.memo = request.POST['memo']
        reason = request.POST['reason']
        if name:
            try:
                tempdwdm = get_object_or_404(models.DWDM,name=name)
            except:
                dwdm.name = name
            else:
                if dwdm != tempdwdm:
                    messages.error(request,'修改失败,DWDM命名:%s已经存在' %name)
                    return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
        else:    
            messages.error(request,'修改失败,DWDM命名不能为空')
            return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
        if manufacturer:
            try:
                tempmanufacturer = get_object_or_404(models.Manufacturer,name=manufacturer)
            except:
                messages.error(request,'修改失败,厂商%s不存在' %manufacturer)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
            else:
                dwdm.manufacturer = tempmanufacturer
        else:
            dwdm.manufacturer = None
        if modelnumber:
            try:
                tempmodelnumber = get_object_or_404(models.Modelnumber,name=modelnumber)
            except:
                messages.error(request,'修改失败,厂商%s不存在' %modelnumber)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
            else:
                dwdm.modelnumber = tempmodelnumber
        else:
            dwdm.modelnumber = None                
        if maintainer:
            try:
                tempmaintainer = User.objects.get(username=maintainer)
            except:
                messages.error(request,'修改失败,维护人%s不存在' %maintainer)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
            else:
                dwdm.maintainer = tempmaintainer
        else:
            dwdm.maintainer = None
        if  machineroom_a:
            try:
                tempmachineroom_a = get_object_or_404(models.MachineRoom,name=machineroom_a)
            except:
                messages.error(request,'修改失败,起始端机房%s不存在' %machineroom_a)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id) 
            else:
                dwdm.machineroom_a = tempmachineroom_a
        else:
            dwdm.machineroom_a = None        
        if  cabinet_a:
            try:
                tempcabinet_a = get_object_or_404(models.Cabinet,name=cabinet_a)
            except:
                messages.error(request,'修改失败,起始端机柜%s不存在' %cabinet_a)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
            else:
                dwdm.cabinet_a = tempcabinet_a
        else:
            dwdm.cabinet_a = None
        if  machineroom_z:
            try:
                tempmachineroom_z = get_object_or_404(models.MachineRoom,name=machineroom_z)
            except:
                messages.error(request,'修改失败,终止端机房%s不存在' %machineroom_z)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id) 
            else:
                dwdm.machineroom_z = tempmachineroom_z
        else:
            dwdm.machineroom_z = None        
        if  cabinet_z:
            try:
                tempcabinet_z = get_object_or_404(models.Cabinet,name=cabinet_z)
            except:
                messages.error(request,'修改失败,终止端机柜%s不存在' %cabinet_z)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
            else:
                dwdm.cabinet_z = tempcabinet_z
        else:
            dwdm.cabinet_z = None
        if  device_a_number:
            try:
                tempasset = get_object_or_404(models.Asset,name=device_a_number)
            except:
                messages.error(request,'修改失败,起始端设备%s不存在' %device_a_number)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
            else:
                netowrkdevice = get_object_or_404(models.NetworkDevice,asset=tempasset)
                if netowrkdevice.networkdevice_type == 3:
                    dwdm.device_a_number = tempasset
                else:
                    messages.error(request,'修改失败,起始端设备%s不是波分设备' %device_a_number)
                    return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
        else:
            dwdm.device_a_number = None
        if  device_z_number:
            try:
                tempasset = get_object_or_404(models.Asset,name=device_z_number)
            except:
                messages.error(request,'修改失败,终止端设备%s不存在' %device_z_number)
                return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
            else:
                netowrkdevice = get_object_or_404(models.NetworkDevice,asset=tempasset)
                if netowrkdevice.networkdevice_type == 3:
                    dwdm.device_z_number = tempasset
                else:
                    messages.error(request,'修改失败,起始端设备%s不是波分设备' %device_z_number)
                    return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
        else:
            dwdm.device_z_number = None
        dwdm.save()
        dwdm = get_object_or_404(models.DWDM,id=dwdm_id)
        if olddwdm.name != dwdm.name:
            change = 'DWDM名称由:“%s”修改为:“%s”' %(olddwdm.name,dwdm.name)
            detaillist.append(change)
        if olddwdm.manufacturer != dwdm.manufacturer:
            change = 'DWDM设备厂商由:“%s”修改为:“%s”' %(olddwdm.manufacturer,dwdm.manufacturer)
            detaillist.append(change) 
        if olddwdm.modelnumber != dwdm.modelnumber:
            change = 'DWDM设备型号由:“%d”修改为:“%d”' %(olddwdm.modelnumber,dwdm.modelnumber)
            detaillist.append(change)
        if olddwdm.status != dwdm.status:
            change = 'DWDM状态由:“%s”修改为:“%s”' %(olddwdm.get_status_display(),dwdm.get_status_display())
            detaillist.append(change)
        if olddwdm.business_unit != dwdm.business_unit:
            change = 'DWDM业务线由:“%s”修改为:“%s”' %(olddwdm.get_business_unit_display(),dwdm.get_business_unit_display())
            detaillist.append(change)
        if olddwdm.oeo != dwdm.oeo:
            change = 'DWDM自用状态由:“%s”修改为:“%s”' %(olddwdm.get_oeo_display(),dwdm.get_oeo_display())
            detaillist.append(change)
        if olddwdm.olp != dwdm.olp:
            change = 'DWDM是否启用OLP由:“%s”修改为:“%s”' %(olddwdm.get_olp_display(),dwdm.get_olp_display())
            detaillist.append(change)              
        if olddwdm.high != dwdm.high:
            change = 'DWDM设备高度由:“%s”修改为:“%s”' %(olddwdm.high,dwdm.high)
            detaillist.append(change)
        if olddwdm.maintainer != dwdm.maintainer:
            change = 'DWDM维护人由:“%s”修改为:“%s”' %(olddwdm.maintainer,dwdm.maintainer)
            detaillist.append(change)
        if olddwdm.mux != dwdm.mux:
            change = '合分波器由:“%s”修改为:“%s”' %(olddwdm.mux,dwdm.mux)
            detaillist.append(change)
        if olddwdm.ba != dwdm.ba:
            change = 'BA放大器由:“%s”修改为:“%s”' %(olddwdm.ba,dwdm.ba)
            detaillist.append(change)
        if olddwdm.pa != dwdm.pa:
            change = 'PA放大器由:“%s”修改为:“%s”' %(olddwdm.pa,dwdm.pa)
            detaillist.append(change)
        if olddwdm.dcm != dwdm.dcm:
            change = 'DCM色散补偿由:“%s”修改为:“%s”' %(olddwdm.dcm,dwdm.dcm)
            detaillist.append(change)
        if olddwdm.machineroom_a != dwdm.machineroom_a:
            change = 'DWDM起始端机房单元由:“%s”修改为:“%s”' %(olddwdm.machineroom_a,dwdm.machineroom_a)
            detaillist.append(change)
        if olddwdm.cabinet_a != dwdm.cabinet_a:
            change = 'DWDM起始端机架由:“%s”修改为:“%s”' %(olddwdm.cabinet_a,dwdm.cabinet_a)
            detaillist.append(change)                                                                                                                            
        if olddwdm.machineroom_z != dwdm.machineroom_z:
            change = 'DWDM终止端机房单元由:“%s”修改为:“%s”' %(olddwdm.machineroom_z,dwdm.machineroom_z)
            detaillist.append(change)                                                               
        if olddwdm.cabinet_z != dwdm.cabinet_z:
            change = 'DWDM终止端机架由:“%s”修改为:“%s”' %(olddwdm.cabinet_z,dwdm.cabinet_z)
            detaillist.append(change)                                                                                                                            
        if olddwdm.device_a_number != dwdm.device_a_number:
            change = '起始端设备固资编号由:“%s”修改为:“%s”' %(olddwdm.device_a_number,dwdm.device_a_number)
            detaillist.append(change) 
        if olddwdm.device_z_number != dwdm.device_z_number:
            change = '终止端设备固资编号由:“%s”修改为:“%s”' %(olddwdm.device_z_number,dwdm.device_z_number)
            detaillist.append(change)
        if olddwdm.memo != dwdm.memo:
            change = 'DWDM备注由:“%s”修改为:“%s”' %(olddwdm.memo,dwdm.memo)
            detaillist.append(change)
        detail = '; '.join(detaillist)
        if detail:
           eventlog = models.DwdmEventLog(dwdm=dwdm,event_type=1,reason=reason,detail=detail,user=request.user)
           eventlog.save()                                                                         
           return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
        else:
           messages.error(request,"无数据变化")
           return HttpResponseRedirect('/dwdmdetail/%s' %dwdm_id)
    else:
        channel = models.Channel.objects.filter(dwdm_id=dwdm_id)
        machineroom = models.MachineRoom.objects.all()
        eventlog = models.DwdmEventLog.objects.filter(dwdm=dwdm_id)
        circuit = models.Circuit.objects.filter(dwdm_id=dwdm_id)
        return render(request, 'assets/dwdmdetail.html',{'dwdm':dwdm,'eventlog':eventlog,'circuit':circuit,'channel':channel,'machineroom':machineroom})

login_required(login_url='/login/')
def channel(request):
    '''波道查询'''
    if request.GET:
        name=request.GET['name']
        dwdm=request.GET['dwdm']
        status = request.GET['status']
        customer = request.GET['customer']
        networkdevice_a = request.GET['networkdevice_a']
        networkdevice_z = request.GET['networkdevice_z']
        port_a = request.GET['port_a']
        port_z = request.GET['port_z']    
        name_split = name.split()
        name_qlist = []
        for key in name_split:
            name_qlist.append(Q(name__icontains=key))
        if name_qlist:
            name_channel = models.Channel.objects.filter(reduce(operator.or_, name_qlist))
        else:
           name_channel = models.Channel.objects.all()
        qlist=[Q(status__icontains=status),Q(customer__icontains=customer)]
        if dwdm:
            qlist.append(Q(dwdm__name__icontains=dwdm))
        else:
            qlist.append(Q(dwdm__name__icontains=dwdm) | Q(dwdm__name__isnull=True))
        if networkdevice_a:
            qlist.append(Q(networkdevice_a__hostname__icontains=networkdevice_a))
        else:
            qlist.append(Q(networkdevice_a__hostname__icontains=networkdevice_a) | Q(networkdevice_a__hostname__isnull=True))
        if networkdevice_z:
            qlist.append(Q(networkdevice_z__hostname__icontains=networkdevice_z))
        else:
            qlist.append(Q(networkdevice_z__hostname__icontains=networkdevice_z) | Q(networkdevice_z__hostname__isnull=True))
        if port_a:
            qlist.append(Q(port_a__name__icontains=port_a))
        else:
            qlist.append(Q(port_a__name__icontains=port_a) | Q(port_a__name__isnull=True))
        if port_z:
            qlist.append(Q(port_z__name__icontains=port_z))
        else:
            qlist.append(Q(port_z__name__icontains=port_z) | Q(port_z__name__isnull=True))
        other_channel = models.Channel.objects.filter(reduce(operator.and_, qlist))
        channel = other_channel & name_channel
        return render(request, 'assets/channel.html',{'channel':channel} )
    else:
       return render(request, 'assets/channel.html')


login_required(login_url='/login/')
def channeldetail(request,channel_id):
    '''波道详细'''
    channel = get_object_or_404(models.Channel,id=channel_id)
    if request.POST:
        oldchannel = get_object_or_404(models.Channel,id=channel_id)
        detaillist=[]
        name=request.POST['name']
        dwdm=request.POST['dwdm']
        channel.status = request.POST['status']
        channel.customer = request.POST['customer']
        networkdevice_a = request.POST['networkdevice_a']
        networkdevice_z = request.POST['networkdevice_z']
        port_a = request.POST['port_a']
        port_z = request.POST['port_z']
        channel.memo = request.POST['memo']
        reason = request.POST['reason']
        if name:
            try:
                tempchannel = get_object_or_404(models.Channel,name=name)
            except:
                channel.name = name
            else:
                if channel != tempchannel:
                    messages.error(request,'修改失败,波道命名:%s已经存在' %name)
                    return HttpResponseRedirect('/channeldetail/%s' %channel_id)
        else:    
            messages.error(request,'修改失败,波道命名不能为空')
            return HttpResponseRedirect('/channeldetail/%s' %channel_id)
        if dwdm:
            try:
                tempdwdm = get_object_or_404(models.DWDM,name=dwdm)
            except:
                messages.error(request,'修改失败,DWDM“%s”不存在' %dwdm)
                return HttpResponseRedirect('/channeldetail/%s' %channel_id)
            else:
                channel.dwdm = tempdwdm
        else:
            channel.dwdm = None
        if networkdevice_a:
            try:
                tempnetworkdevice_a = get_object_or_404(models.Asset,hostname=networkdevice_a)
            except:
                messages.error(request,'修改失败,起始端设备“%s”不存在' %networkdevice_a)
                return HttpResponseRedirect('/channeldetail/%s' %channel_id)
            else:
                channel.networkdevice_a = tempnetworkdevice_a
        else:
            channel.networkdevice_a = None                
        if networkdevice_z:
            try:
                tempnetworkdevice_z = get_object_or_404(models.Asset,hostname=networkdevice_z)
            except:
                messages.error(request,'修改失败,终止端设备“%s”不存在' %networkdevice_z)
                return HttpResponseRedirect('/channeldetail/%s' %channel_id)
            else:
                channel.networkdevice_z = tempnetworkdevice_z
        else:
            channel.networkdevice_a = None   
        if  port_a:
            if tempnetworkdevice_a:
                try:
                    tempport_a = get_object_or_404(models.Asset,name=port_a,networkdevice=tempnetworkdevice_a)
                except:
                    messages.error(request,'修改失败,起始端设备“%s”不存在端口“%s”不存在' %(tempnetworkdevice_a,port_a))
                    return HttpResponseRedirect('/channeldetail/%s' %channel_id) 
                else:
                    channel.port_a = tempport_a
            else:
                messages.error(request,'修改失败,起始端填入端口时，网络设备不能为空')
                return HttpResponseRedirect('/channeldetail/%s' %channel_id)    
        else:
            channel.port_a = None
        if  port_z:
            if tempnetworkdevice_z:
                try:
                    tempport_a = get_object_or_404(models.Asset,name=port_a,networkdevice=tempnetworkdevice_z)
                except:
                    messages.error(request,'修改失败,起始端设备“%s”不存在端口“%s”不存在' %(tempnetworkdevice_z,port_z))
                    return HttpResponseRedirect('/channeldetail/%s' %channel_id) 
                else:
                    channel.port_z = tempport_z
            else:
                messages.error(request,'修改失败,起始端填入端口时，网络设备不能为空')
                return HttpResponseRedirect('/channeldetail/%s' %channel_id)    
        else:
            channel.port_z = None
        channel.save()
        channel = get_object_or_404(models.Channel,id=channel_id)
        if oldchannel.name != channel.name:
            change = '波道名称由:“%s”修改为:“%s”' %(oldchannel.name,channel.name)
            detaillist.append(change)
        if oldchannel.dwdm != channel.dwdm:
            change = 'DWDM由:“%s”修改为:“%s”' %(oldchannel.dwdm,channel.dwdm)
            detaillist.append(change) 
        if oldchannel.customer != channel.customer:
            change = '客户由:“%d”修改为:“%d”' %(oldchannel.customer,channel.customer)
            detaillist.append(change)
        if oldchannel.status != channel.status:
            change = '状态由:“%s”修改为:“%s”' %(oldchannel.get_status_display(),channel.get_status_display())
            detaillist.append(change)
        if oldchannel.networkdevice_a != channel.networkdevice_a:
            change = '起始端设备由:“%s”修改为:“%s”' %(oldchannel.networkdevice_a,channel.networkdevice_a)
            detaillist.append(change)
        if oldchannel.port_a != channel.port_a:
            change = '起始端端口由:“%s”修改为:“%s”' %(oldchannel.port_a,channel.port_a)
            detaillist.append(change)
        if oldchannel.networkdevice_z != channel.networkdevice_z:
            change = '终止端设备由:“%s”修改为:“%s”' %(oldchannel.networkdevice_z,channel.networkdevice_z)
            detaillist.append(change)
        if oldchannel.port_z != channel.port_z:
            change = '终止端端口由:“%s”修改为:“%s”' %(oldchannel.port_z,channel.port_z)
            detaillist.append(change)
        if oldchannel.memo != channel.memo:
            change = '备注由:“%s”修改为:“%s”' %(oldchannel.memo,channel.memo)
            detaillist.append(change)
        detail = '; '.join(detaillist)
        if detail:
           eventlog = models.DwdmEventLog(channel=channel,event_type=1,reason=reason,detail=detail,user=request.user)
           eventlog.save()
           return HttpResponseRedirect('/channeldetail/%s' %channel_id)
        else:
           messages.error(request,"无数据变化")
           return HttpResponseRedirect('/channeldetail/%s' %channel_id)
    else:
        eventlog = models.DwdmEventLog.objects.filter(channel=channel_id)
        return render(request, 'assets/channeldetail.html',{'channel':channel,'eventlog':eventlog})

@login_required(login_url='/login/')
def conipnet(request):
    if request.GET:
       name=request.GET['name']
       name_split = name.split()
       name_qlist = []
       for key in name_split:
           name_qlist.append(Q(name__icontains=key))
       if name_qlist:
          name_conipnet = models.ConIpNet.objects.filter(reduce(operator.or_, name_qlist))
       else:
          name_conipnet = models.ConIpNet.objects.all()
       ipnet_status = request.GET['ipnet_status']
       ipnet_type = request.GET['ipnet_type']
       zone = request.GET['zone']
       vlan = request.GET['vlan']      
       usage=request.GET['usage']
       networkdevice_a = request.GET['networkdevice_a']
       networkdevice_z = request.GET['networkdevice_z']
       qlist=[Q(ipnet_status__icontains=ipnet_status),Q(ipnet_type__icontains=ipnet_type),Q(zone__icontains=zone),Q(usage__icontains=usage)]
       if vlan:
          qlist.append(Q(vlan__icontains=vlan))
       else:
          qlist.append(Q(vlan__icontains=vlan) | Q(vlan__isnull=True))
       if networkdevice_a:
          qlist.append(Q(networkdevice_a__hostname__icontains=networkdevice_a))
       else:
          qlist.append(Q(networkdevice_a__hostname__icontains=networkdevice_a) | Q(networkdevice_a__hostname__isnull=True))
       if networkdevice_z:
          qlist.append(Q(networkdevice_z__hostname__icontains=networkdevice_z))
       else:
          qlist.append(Q(networkdevice_z__hostname__icontains=networkdevice_z) | Q(networkdevice_z__hostname__isnull=True))
       other_conipnet = models.ConIpNet.objects.filter(reduce(operator.and_, qlist))
       conipnet = other_conipnet & name_conipnet
       return render(request, 'assets/conipnet.html',{'conipnet':conipnet} )
    elif request.POST:
        if request.POST.get('submit') == 'editconipnet':
            detaillist=[]
            name = request.POST['name']
            if name:
                try:
                    conipnet = get_object_or_404(models.ConIpNet,name=name)
                except:
                    messages.error(request,"修改失败，网段不存在")
                    return HttpResponseRedirect('/conipnet/')
                else:
                    oldconipnet = get_object_or_404(models.ConIpNet,name=name)   
            else:
                messages.error(request,"修改失败，网段名不能为空")
                return HttpResponseRedirect('/conipnet/')
            conipnet.ipnet_status = request.POST['ipnet_status']
            conipnet.ipnet_type = request.POST['ipnet_type']
            conipnet.zone = request.POST['zone']
            networkdevice_a = request.POST['networkdevice_a']
            networkdevice_z = request.POST['networkdevice_z']
            conipnet.port_a = request.POST['port_a']
            conipnet.port_z = request.POST['port_z']
            ip_a = request.POST['ip_a']
            ip_z = request.POST['ip_z']
            conipnet.vlan = request.POST['vlan'] if request.POST['vlan'] else None
            conipnet.usage = request.POST['usage']
            conipnet.memo = request.POST['memo']
            if networkdevice_a:
                try:
                    tempnetworkdevice = get_object_or_404(models.Asset,hostname=networkdevice_a)
                except:
                    messages.error(request,"修改失败，起始端设备不存在")
                    return HttpResponseRedirect('/conipnet/')
                else:
                    conipnet.networkdevice_a = tempnetworkdevice
            else:
                conipnet.networkdevice_a = None
            if networkdevice_z:
                try:
                    tempnetworkdevice = get_object_or_404(models.Asset,hostname=networkdevice_z)
                except:
                    messages.error(request,"修改失败，终止端设备不存在")
                    return HttpResponseRedirect('/conipnet/')
                else:
                    conipnet.networkdevice_z = tempnetworkdevice
            else:
                conipnet.networkdevice_z = None
            if ip_a:
                if ip_a not in IP(name):
                    messages.error(request,"修改失败，起始端IP不在网段内")
                    return HttpResponseRedirect('/conipnet/')
                else:
                    conipnet.ip_a = ip_a
            else:
                conipnet.ip_a = None
            if ip_z:
                if ip_z not in IP(name):
                    messages.error(request,"修改失败，终止端IP不在网段内")
                    return HttpResponseRedirect('/conipnet/')
                else:
                    conipnet.ip_z = ip_a
            else:
                conipnet.ip_z = None
            conipnet.save()
            newconipnet = get_object_or_404(models.ConIpNet,name=name)
            if oldconipnet.name != newconipnet.name:
                change = '网段名称由:“%s”修改为“%s”' %(oldconipnet.name,newconipnet.name)
                detaillist.append(change)
            if oldconipnet.ipnet_status != newconipnet.ipnet_status:
                change = '网段状态由:“%s”修改为“%s”' %(oldconipnet.get_ipnet_status_display(),newconipnet.get_ipnet_status_display())
                detaillist.append(change)
            if oldconipnet.ipnet_type != newconipnet.ipnet_type:
                change = '网段类型由:“%s”修改为“%s”' %(oldconipnet.get_ipnet_type_display(),newconipnet.get_ipnet_type_display())
                detaillist.append(change)
            if oldconipnet.zone != newconipnet.zone:
                change = '网段类型由:“%s”修改为“%s”' %(oldconipnet.get_zone_display(),newconipnet.get_zone_display())
                detaillist.append(change) 
            if oldconipnet.networkdevice_a != newconipnet.networkdevice_a:
                change = '网段起始端设备由:“%s”修改为“%s”' %(oldconipnet.networkdevice_a,newconipnet.networkdevice_a)
                detaillist.append(change)
            if oldconipnet.networkdevice_z != newconipnet.networkdevice_z:
                change = '网段终止端设备由:“%s”修改为“%s”' %(oldconipnet.networkdevice_z,newconipnet.networkdevice_a)
                detaillist.append(change)
            if oldconipnet.port_a != newconipnet.port_a:
                change = '网段起始端端口由:“%s”修改为“%s”' %(oldconipnet.port_a,newconipnet.port_a)
                detaillist.append(change)
            if oldconipnet.port_z != newconipnet.port_z:
                change = '网段终止端端口由:“%s”修改为“%s”' %(oldconipnet.port_z,newconipnet.port_z)
                detaillist.append(change)
            if oldconipnet.ip_a != newconipnet.ip_a:
                change = '网段起始端IP由:“%s”修改为“%s”' %(oldconipnet.ip_a,newconipnet.ip_a)
                detaillist.append(change)
            if oldconipnet.ip_z != newconipnet.ip_z:
                change = '网段起始端IP由:“%s”修改为“%s”' %(oldconipnet.ip_z,newconipnet.ip_z)
                detaillist.append(change)  
            if oldconipnet.vlan != newconipnet.vlan:
                change = '网段VLAN由:“%s”修改为“%s”' %(oldconipnet.vlan,newconipnet.vlan)
                detaillist.append(change)  
            if oldconipnet.usage != newconipnet.usage:
                change = '网段用途由:“%s”修改为“%s”' %(oldconipnet.usage,newconipnet.usage)
                detaillist.append(change)  
            if oldconipnet.memo != newconipnet.memo:
                change = '网段备注由:“%s”修改为“%s”' %(oldconipnet.memo,newconipnet.memo)
                detaillist.append(change)
            return HttpResponseRedirect('/conipnet/')                           
        elif request.POST.get('submit') == 'delconipnet':
            name = request.POST['name']
            if name:
                try:
                    conipnet = get_object_or_404(models.ConIpNet,name=name)
                except:
                    messages.error(request,"删除失败，网段不存在")
                    return HttpResponseRedirect('/conipnet/')
                else:
                    conipnet.delete()
                    return HttpResponseRedirect('/conipnet/')   
            else:
                messages.error(request,"删除失败，网段名不能为空")
                return HttpResponseRedirect('/conipnet/')
    else:
       return render(request, 'assets/conipnet.html')